<?php
namespace app\modules\pay\services;

use app\common\services\BaseService;
use app\config\Constants;
use app\models\MerchantPayment;
use app\models\PaymentLog;
use app\modules\pay\provider\PayFactory;
use app\utils\QueueUtil;
use app\utils\UserUtil;
use Carbon\Carbon;

class PaymentService extends BaseService{

    /**
     * 支付
     * @param integer $oder_id 订单ID
     * @param integer $payment 支付方式
     * @return array|bool
     * @throws \Throwable
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\base\UserException
     * @throws \yii\db\StaleObjectException
     */
    public static function pay($oder_id,$payment){
        $user = UserUtil::getModuleUserIdentity("pay");
        $order = GoodsOrderService::getInfoById($user->getId(),$oder_id);
        if(!$order){
            self::setError(\Yii::t("app","订单不存在"));
            return false;
        }
        if(empty($payment)){
            $payment = $order->pay_method;
        }
        //订单状态
        if($order->status != Constants::ORDER_WAIT && $order->status != Constants::ORDER_WAIT_PAYMENT){
            self::setError(\Yii::t("app","订单状态错误"));
            return false;
        }
        //重复支付
        if($order->pay_status == Constants::PAY_STATUS_SUCCESS){
            self::setError(\Yii::t("app","请勿重复支付!"));
            return false;
        }

        $merchant = MerchantService::getInfoById($order->merchant_id);
        if(!$merchant){
            self::setError(\Yii::t("app","店铺不存在"));
            return false;
        }

        //货到付款
        if($payment == Constants::PAY_DELIVERY){
            $order->setAttribute("pay_method",Constants::PAY_DELIVERY);
            $order->setAttribute("pay_status",Constants::PAY_STATUS_WAIT);
            $order->update();
            QueueUtil::fanout(Constants::MSG_TYPE_ORDER,Constants::ORDER_WAIT,['order_no'=>$order->order_no]);
            return [
                'payment'=>$order->pay_method,
                'pay_params'=>""
            ];
        }

        //支付渠道
        $config =  MerchantPayment::findOne($merchant->merchant_id);
        if(!$config){
            self::setError(\Yii::t("app","该商户不支持该支付方式,请更换支付方式"));
            return false;
        }
        //用户是否为微信端注册
        $credential = UserService::getCredential($user->getId(),Constants::WECHAT);
        if($payment == Constants::PAY_WECHAT && !$credential){
            self::setError(\Yii::t("app","非小程序端无法使用微信支付"));
            return false;
        }
        //平台订单号
        $platform_order_no = date("YmdHis") . rand(1000,9999);
        $result = PayFactory::getPayCode($payment,$platform_order_no,$order->real_price,"yijiegou",$credential ? $credential->username : null,$config->getConfig());
        $order->setAttribute("pay_method",$payment);
        $order->update();

        $model = new PaymentLog();
        $model->setAttribute("order_id",$order->order_id);
        $model->setAttribute("platform_order_no",$platform_order_no);
        $model->setAttribute("payment",$payment);
        $model->setAttribute("add_time",Carbon::now());
        $model->insert();

        return [
            'payment'=>$order->pay_method,
            'pay_params'=>$result['data']
        ];
    }

    /**
     * 根据来源返回支付方式
     * @param $source
     * @param $merchant_id
     * @return array
     */
    public static function supportList($source,$merchant_id){
        $model = MerchantPayment::findOne($merchant_id);
        $list = [['payment'=>Constants::PAY_DELIVERY,'payment_name'=>'货到付款']];
        if(!$model || empty($list)){
            return $list;
        }

        if($source == Constants::SOURCE_MINI){
            $list[] =['payment'=>Constants::PAY_WECHAT,'payment_name'=>'微信支付'];
        }
        if($source == Constants::SOURCE_H5){
            $list[] = ['payment'=>Constants::PAY_ALIPAY,'payment_name'=>'支付宝'];
        }

        return $list;
    }

    /**
     * 返回订单支持的支付方式
     * @param $source
     * @param $order_id
     * @return array|bool
     * @throws \Throwable
     * @throws \yii\base\InvalidConfigException
     */
    public static function method($source,$order_id){
        $user = UserUtil::getModuleUserIdentity("pay");
        $order = GoodsOrderService::getInfoById($user->getId(),$order_id);
        if(!$order){
            self::setError(\Yii::t("app","订单不存在"));
            return false;
        }
        return self::supportList($source,$order->merchant_id);
    }
}